package com.ch.dream;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.AsyncTask;
import android.os.Handler;

import com.ch.dream.activity.main.MainMenuActivity;
import com.ch.dream.asynctask.LoginReplyNumRequstAsyncTask;
import com.ch.dream.asynctask.MainRequestAsyncTask;
import com.ch.dream.bean.PhoneInfoBean;
import com.ch.dream.common.CommonData;
import com.ch.dream.common.CommonRequestUrl;
import com.ch.dream.common.CommonResult;
import com.ch.dream.net.MyHttpAPI;
import com.ch.dream.tools.PhoneTools;
import com.ch.dream.tools.UtilTools;
import com.ch.dream.tools.ViewTools;

public class UpdateManager {
	
	public static String UPDATE = CommonRequestUrl.HTTPURL+"UpdateService";//更新路径
		
	public static String downLoadUrl = "";//下载路径
	private static MyHttpAPI myHttpAPI =new MyHttpAPI(UPDATE);
	private static Integer nowVersionCode;
	private static String clientName;
	private static Activity mActivity;
	private static JSONObject jsonObject;
	private static Handler handler;
	private static ProgressDialog progressDialog;
	public static void update(){
		try {
			mActivity = CommonData.currentActivity;
			PackageInfo packageInfo =mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0);
			nowVersionCode =packageInfo.versionCode;
			clientName = packageInfo.packageName;
			progressDialog = UtilTools.getDownProgress(mActivity, "软件下载", "正在下载中，请稍后...", new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					dialog.dismiss();
					handler = null;
					UtilTools.isStop = true;
				}
			});
			handler =UtilTools.getDownLoadHandler(mActivity, "com.ch.dream", progressDialog);
			new UpdateRequest().execute();
		} catch (Exception e) {
		}
		
	}
	
	public static class UpdateRequest extends AsyncTask<Void, Void, Boolean>{

		@Override
		protected Boolean doInBackground(Void... params) {
			JSONObject jsonParams = new JSONObject();
			try{
				jsonParams.put("clientName", clientName);
				jsonParams.put("versionCode", nowVersionCode);
				jsonObject = myHttpAPI.requestForJson(jsonParams);
				if(jsonObject!=null &&  CommonResult.SUCCESS.equals(jsonObject.getString("result")) && "true".equals(jsonObject.getString("hasUpdate"))){
					return true;
				}else{
					return false;
				}
			}catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result){
				try{
					ViewTools.showConfirm(mActivity, "升级提示","安装包大小:"+jsonObject.getString("size")+"\n"+jsonObject.getString("message"), "升级", "取消", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							UtilTools.isStop = false;
							progressDialog.show();
							new Thread(new Runnable() {
								@Override
								public void run() {
									try{
										UtilTools.downLoadWithHandlerFromUrl(mActivity,jsonObject.getString("downloadUrl"),jsonObject.getString("clientName"), handler);
									}catch (Exception e) {
										e.printStackTrace();
									}
									
								}
							}).start();
						}
					},new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							initLogin();
						}
					});
				}catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				initLogin();
			}
		}
	}
	
	private static void initLogin(){
		try{
			addBaseInfo();
//			SharedPreferences  spDate =activity.getSharedPreferences(CommonData.MYDATE,Context.MODE_PRIVATE);
			SharedPreferences  spUserInfo =mActivity.getSharedPreferences(CommonData.USERINFO,Context.MODE_PRIVATE);
//			String date =spDate.getString("date", "");
//			if(!"".equals(date)){
//				if(isPassDay(date)){//过一天则清除回复数
//					UtilTools.clearSharedPreferences(activity,CommonData.REPLYNUM);
//				}else{
//				}
//				
//			}else{
//				UtilTools.clearSharedPreferences(activity,CommonData.REPLYNUM);
//			}
			JSONObject json =new JSONObject();
			json.put("userName",spUserInfo.getString("userName",""));
			json.put("password",spUserInfo.getString("password",""));
			json.put("IMEI", CommonData.IMEI);
			LoginReplyNumRequstAsyncTask loginReplyNumRequstAsyncTask=new LoginReplyNumRequstAsyncTask(mActivity,null){
				@Override
				protected void onPostExecute(Object result) {
					super.onPostExecute(result);
//						SharedPreferences  spReply =activity.getSharedPreferences(CommonData.REPLYNUM,Context.MODE_PRIVATE);
//						if(spReply==null){
//							UtilTools.setIntSharedPreferences(activity, CommonData.REPLYNUM,"timeNum",CommonData.DEFAULTREPLYNUM);
//							UtilTools.setIntSharedPreferences(activity, CommonData.REPLYNUM,"placeNum",CommonData.DEFAULTREPLYNUM);
//							UtilTools.setIntSharedPreferences(activity, CommonData.REPLYNUM,"peopleNum",CommonData.DEFAULTREPLYNUM);
//							UtilTools.setIntSharedPreferences(activity, CommonData.REPLYNUM,"eventNum",CommonData.DEFAULTREPLYNUM);
//							UtilTools.setIntSharedPreferences(activity, CommonData.REPLYNUM,"getNum",CommonData.DEFAULTREPLYNUM);
//						}
					Intent intent = new Intent(mActivity,MainMenuActivity.class);
					mActivity.startActivity(intent);
					mActivity.finish();
				}
			};
			loginReplyNumRequstAsyncTask.execute(json);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 记录用户的基本信息
	 */
	private static void addBaseInfo(){
		try{
			new MainRequestAsyncTask(mActivity,null).execute(getPhoneInfo().getJsonObject());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取手机基本信息
	 */
	private static PhoneInfoBean getPhoneInfo() {
		PhoneInfoBean phoneInfo = PhoneTools.getPhoneInfo(mActivity);
		CommonData.IMEI = phoneInfo.getPhoneIMEI();
		return phoneInfo;
	}
}
